package com.lifeng.controller;

import com.baomidou.mybatisplus.core.conditions.Wrapper;
import com.baomidou.mybatisplus.core.toolkit.Wrappers;
import com.lifeng.common.util.PageResult;
import com.lifeng.common.util.Result;
import com.lifeng.entity.Book;
import com.lifeng.entity.Type;
import com.lifeng.service.IBookService;
import com.lifeng.service.ITypeService;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.*;

import java.util.Arrays;
import java.util.List;
import java.util.Map;

/**
 * <p>
 *  前端控制器
 * </p>
 *
 * @author lifeng
 * @since 2025-01-13
 */
@RestController
@RequestMapping("/type")
public class TypeController {
	@Autowired
	private ITypeService typeService;
	@Autowired
	private IBookService bookService;
	@GetMapping("/list")
	public Result list(){
		return Result.ok().data("list", typeService.list());
	}

	// 分页查询（不带条件）
	@GetMapping("/findByPage/{page}/{pageSize}")
	public Result findByPage(@PathVariable("page") Integer page,
							 @PathVariable("pageSize") Integer pageSize) {
		PageResult<Type> pr = typeService.findByPage(page,pageSize);
		return Result.ok().data("pr",pr);
	}
	// 分页查询（带条件）
	@PostMapping("/search/{page}/{pageSize}")
	public Result search(@PathVariable("page") Integer page,
						 @PathVariable("pageSize") Integer pageSize,
						 @RequestBody Map<String,String> params){
		PageResult<Type> pr = typeService.search(page,pageSize,params.get("tname"));
		return Result.ok().data("pr",pr);
	}

	// 添加
	@PostMapping("/add")
	public Result add(@RequestBody Type type){
		boolean flag = typeService.save(type);
		return flag ? Result.ok().message("添加成功!^v^") : Result.error().message("添加失败!>^<");
	}

	//修改
	@PutMapping("/update")
	public Result update(@RequestBody Type type){
		boolean flag = typeService.updateById(type);
		return flag ? Result.ok().message("修改成功!^v^") : Result.error().message("修改失败!>^<");
	}


	// 批量删除
//	@DeleteMapping("/delete/{ids}")
//	public Result delete(@PathVariable("ids") String ids){
//		String[] temp = ids.split(",");
//		List<String> list = Arrays.asList(temp);
//		return typeService.removeByIds(list) ? Result.ok().message("删除成功!^v^") : Result.error().message("删除失败!>^<");
//	}
	//批量删除，逻辑外键进行检查
	@DeleteMapping("/delete/{ids}")
	public Result delete(@PathVariable("ids") String ids){
		String[] temp = ids.split(",");
		List<String> list = Arrays.asList(temp);
		for(String tid:list)
		{
			System.out.println("lifeng");
			Wrapper<Book> wrapper = Wrappers
					.<Book>lambdaQuery()
					.eq(Book::getTid, tid);
			List<Book> books = bookService.list(wrapper);
			if(!books.isEmpty()) return Result.error().message("删除失败!>^<,有相关图书依赖该类型！");
		};
		return typeService.removeByIds(list) ? Result.ok().message("删除成功!^v^") : Result.error().message("删除失败!>^<");
	}
}
